import router, {constantRoutes, errorRoutes} from '@/router'
import _ from 'lodash'
import {mergeArray} from "@/utils/index.js";

const modules = import.meta.glob('../views/**/*.vue')

/**
 * Filter asynchronous routing tables by recursion
 * @param menuList asyncRoutes
 * @param
 */
export function filterAsyncRoutes(menuList) {
    const res = []
    menuList.forEach(route => {
        if (route.menuType == 1) {
            // vue3使用的不是webpack的require，而是import.meta.glob，所以这里需要使用动引入需要有所改变
            route.component = modules[`../views${route.component}/index.vue`]
            // route.component = () => import('@/src/views'+route.component+'/index.vue')
            route.meta = {title: route.menuName, icon: route.icon}
            if (route.children && route.children.length > 0) {
                route.children[0].path ? route.redirect = route.children[0].path : null
                // route.children[0].path ? route.redirect = '/' + route.path + '/' + route.children[0].path : null
                route.children = filterAsyncRoutes(route.children)
            }
            // 使用lodash删除多余的属性
            // route = _.omit(route, ['_id', 'updateTime', 'createTime', 'icon', 'menuName', 'parentId', '_v', 'menuState', 'menuCode', 'menuType', 'order', 'action'])
            if (route.children && route.children.length === 0)
                route = _.omit(route, ['children'])
            res.push(route)
        }
    })
    return res
}

const state = {
    menuList: [], // 菜单列表
    addRoutes: [] // 添加的路由
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        const accessedRoutes = _.cloneDeep(constantRoutes)
        // 这里对其子元素children进行了添加路由的操作
        // ，会对constantRoutes的children进行修改，
        // 导致原数组的children也被修改
        state.menuList = accessedRoutes.map(item => {
            if (item.path === '/') {
                item.children = mergeArray(item.children, routes)
                // 添加到真实的路由中
                routes.forEach(r => {
                    router.addRoute(item.name, r)
                })
            }
            return item
        })
        // 添加404页面
        router.addRoute(errorRoutes[0])
    },
    // 从服务器请求的路由
    SET_ADD_ROUTES: (state, routes) => {
        state.addRoutes = routes
    },

    // 删除路由
    SET_REMOVE_ROUTES: (state) => {
      location.reload()
    }
}

const actions = {
    generateRoutes({commit}, menuList = []) {
        // 这里使用了深拷贝，防止对原数组进行修改
        const addRouter = _.cloneDeep(menuList)
        return new Promise(resolve => {
            let accessedRoutes
            accessedRoutes = filterAsyncRoutes(menuList)
            commit('SET_ROUTES', accessedRoutes)
            commit('SET_ADD_ROUTES', addRouter)
            resolve(accessedRoutes)
        })
    },
    // 重新添加路由给搜索页面使用
    addRoutesFn({commit}, menuList) {
        commit('SET_ADD_ROUTES', menuList)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
